package com.example.hobbyplanetserve.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.hobbyplanetserve.entity.MyTUserDetail;
import com.example.hobbyplanetserve.entity.User;
import com.example.hobbyplanetserve.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Component;

@Component
public class DBUserDetailsManager implements UserDetailsManager, UserDetailsPasswordService {
    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        return null;
    }

    @Override
    public void createUser(UserDetails user) {
        User newUser = new User();
        newUser.setUsername(user.getUsername());
        newUser.setPassword(user.getPassword());
        newUser.setRole(0);
        newUser.setStatus(0);
        userMapper.insert(newUser);
    }

    @Override
    public void updateUser(UserDetails user) {

    }

    @Override
    public void deleteUser(String username) {

    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return false;
    }

    /**
     * 从数据库中加载用户信息 不做验证操作
     * @param username
a     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }else{
//            Collection<GrantedAuthority> authorities = new ArrayList<>();
//
//
//            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
//
//            return new org.springframework.security.core.userdetails.User(
//                    user.getUsername(),
//                    user.getPassword(),
//                    true,
//                    true,
//                    true,
//                    true,
//                    authorities
//            );
            MyTUserDetail myTUserDetail=new MyTUserDetail();
            myTUserDetail.setUser(user);
            return myTUserDetail;
        }
    }
}
